package com.chookss.home.audit.project;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.InitDialog;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.base.LoadingFragment;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import scut.carson_ho.searchview.EditText_Clear;

@SuppressLint("ValidFragment")
public class GroupRoleFragment extends LoadingFragment implements OnRefreshListener, OnLoadMoreListener {

    public Context mContext;
    Unbinder unbinder;

    @BindView(R.id.rvView)
    SwipeMenuRecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.logscl)
    ConsecutiveScrollerLayout logscl;
    @BindView(R.id.logNoneTv)
    TextView logNoneTv;

    @BindView(R.id.rlSearch)

    RelativeLayout rlSearch;
    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    private RoleAdapter adapter;
    private List<ContactEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String groupCode = "", groupName = "";
    private String phoneFlag = "1";//0禁止通话1正常
    private String searchParam = "";//关键字

    public GroupRoleFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_group_role, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    public List<ContactEntity> getList() {
        return list;
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        logNoneTv.setText("暂无成员");
        phoneFlag = new ShareUtils().getString(mContext, StaticClass.PHONE_FLAG, "1");
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new RoleAdapter(R.layout.item_group_role, getActivity(), list);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                int width = Utils.dip2px(mContext, 75);
                int height = ViewGroup.LayoutParams.MATCH_PARENT;
                // 注意：哪边不想要菜单，那么不要添加即可。
                SwipeMenuItem addItem = new SwipeMenuItem(mContext)
                        .setBackground(R.color.main_color)
                        .setText("删除")
                        .setTextSize(15)
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
            }

        };
        rv.setSwipeMenuCreator(mSwipeMenuCreator);
        SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {

                new InitDialog(mContext,
                        "提示", "确认要从项目组中删除此员工吗?", "确认", true,
                        new ShareDialogListener() {
                            @Override
                            public void onClick() {
                                deleteData(menuBridge.getAdapterPosition());
                            }
                        }).show();
                menuBridge.closeMenu();
            }
        };
        rv.setSwipeMenuItemClickListener(mMenuItemClickListener);
        rv.setAdapter(adapter);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        searchParam = v.getText().toString();
                        etSearch.setText(searchParam);
                        currentPage = 1;
                        getData();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        searchParam = "";
                        etSearch.setText("");
                        currentPage = 1;
                        getData();
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
    }

    private RefreshLayout refreshLayout;

    public void setGroupCode(String code, String name) {
        groupCode = code;
        groupName = name;
    }
    @Override
    public void onRefresh(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        isEnd = false;
        currentPage = 1;
        getData();
    }

    @Override
    public void onLoadMore(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("groupCode", groupCode);
        if (!Utils.isNull(searchParam)) {
            map.put("searchParam", searchParam);
        }
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<ContactEntity>>>() {
        }.getType(), null, Urls.queryEmployeeByGroupCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ContactEntity>>() {
            @Override
            public void onSuccess(List<ContactEntity> data) {
                dismissLoading();
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (rv == null || llNone == null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    for (int i = 0; i <data.size() ; i++) {
                        ContactEntity contactEntity=data.get(i);
                        contactEntity.setSelect(true);
                        contactEntity.setType("1");
                        list.add(contactEntity);
                    }
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                    rv.setVisibility(View.VISIBLE);
                    rlSearch.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        rv.setVisibility(View.GONE);
                        rlSearch.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                EventBus.getDefault().post(new MyEvent("RefreshGroupRoleNum"));
                loadEnd();

            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("ChoiceContacts_Ok_11")) {
                if (MyApp.contactEntityLogList.size() > 0) {
                    List<String> orgCodeList = new ArrayList<>();
                    List<String> employeeCodeList = new ArrayList<>();
                    for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                        ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                        if (!contactEntity.isHalfSelect()) {
                            if (contactEntity.getType().equals("0")) {
                                orgCodeList.add(contactEntity.getEmployeeCode());
                            } else {
                                employeeCodeList.add(contactEntity.getEmployeeCode());
                            }
                        }
                    }
                    if (orgCodeList.size() > 0) {
                        getServerData(orgCodeList, employeeCodeList);
                    } else {
                        //没有组织，
                        List<ContactEntity> acceptList = new ArrayList<>();
                        for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                            ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                            if (!contactEntity.isHalfSelect()) {
                                acceptList.add(contactEntity);
                                for (int j = 0; j < list.size(); j++) {
                                    ContactEntity contactEntity2 = list.get(j);
                                    if (contactEntity2.getEmployeeCode().equals(contactEntity.getEmployeeCode())) {
                                        acceptList.remove(acceptList.size() - 1);
                                    }
                                }
                            }
                        }
                        showLoading();
                        uploadData(acceptList);
                    }

                }
            }
        }
    }

    private void getServerData(List<String> orgCodeList, List<String> employeeCodeList) {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", JSON.toJSONString(orgCodeList));
        map.put("employeeCode", JSON.toJSONString(employeeCodeList));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.getSelectedEmployee, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<ContactEntity> serverList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            ContactEntity contactEntity = new ContactEntity();
                            contactEntity.setEmployeeName(jsonObject2.getString("employeeName"));
                            contactEntity.setEmployeeCode(jsonObject2.getString("employeeCode"));
                            contactEntity.setHeadPhotoThumbUrl(jsonObject2.getString("headPhotoThumbUrl"));
                            contactEntity.setType("1");
                            contactEntity.setEmpNum("0");
                            contactEntity.setReviewerFlag("0");
                            contactEntity.setHalfSelect(false);
                            contactEntity.setSelect(false);
                            serverList.add(contactEntity);
                            for (int j = 0; j < list.size(); j++) {
                                ContactEntity contactEntity2 = list.get(j);
                                if (contactEntity2.getEmployeeCode().equals(contactEntity.getEmployeeCode())) {
                                    serverList.remove(serverList.size() - 1);
                                }
                            }
                        }
                        uploadData(serverList);
                    } else {
                        dismissLoading();
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void uploadData(List<ContactEntity> employeeCodeList) {
        //把选择的部门里面的人全部查出来
        Map<String, String> map = new HashMap<>();
        map.put("groupCode", groupCode);
        String employeeCode = "";
        for (int i = 0; i < employeeCodeList.size(); i++) {
            if (i == 0) {
                employeeCode = employeeCodeList.get(i).getEmployeeCode();
            } else {
                employeeCode = employeeCode + "," + employeeCodeList.get(i).getEmployeeCode();
            }
        }
        map.put("employeeCode", employeeCode);
        MyHttpRequest.postRequest(Urls.insertEmployee, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshGroupRecord"));
                        currentPage = 1;
                        getData();
                    } else {
                        dismissLoading();
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }
    private void deleteData(int indexList) {
        //把选择的部门里面的人全部查出来
        Map<String, String> map = new HashMap<>();
        map.put("groupCode", groupCode);
        map.put("employeeCode", list.get(indexList).getEmployeeCode());
        MyHttpRequest.postRequest(Urls.deleteItemEmployee, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        list.remove(indexList);
                        adapter.notifyItemRemoved(indexList);
                        adapter.notifyItemRangeChanged(indexList, list.size() - indexList);
                    } else {
                        dismissLoading();
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }
    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
    }


    class RoleAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Activity context;

        public RoleAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity entity) {
            LinearLayout llPhone = helper.getView(R.id.llPhone);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvPost = helper.getView(R.id.tvPost);
            CircleImageView ivImg = helper.getView(R.id.ivImg);
            ImageView ivPhone = helper.getView(R.id.ivPhone);
            View line = helper.getView(R.id.line);
            GlideUtils.loadAvatar(mContext, entity.getHeadPhotoThumbUrl(), ivImg);
            tvName.setText(entity.getEmployeeName());
            tvPost.setText(entity.getPostName());
            llPhone.setVisibility(View.VISIBLE);
            if ("0".equals(phoneFlag)) {
                ivPhone.setAlpha(0.3f);
            }
            if (helper.getItemPosition() == 0) {
                line.setVisibility(View.GONE);
            } else {
                line.setVisibility(View.VISIBLE);
            }
            llPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if ("1".equals(phoneFlag)) {
                        toPhone(entity.getPhone());
                    } else {
                        MyToast.show("管理员已禁用拨打电话功能");
                    }
                }
            });
            ivImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", entity.getEmployeeCode());
                    mContext.startActivity(intent);
                }
            });
        }
    }

    private void toPhone(String phone) {
        if (!Utils.isNull(phone)) {
            XXPermissions.with(getActivity())
                    .permission(Permission.CALL_PHONE)
                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(List<String> granted, boolean all) {
                            if (all) {
                                Intent callIntent = new Intent(Intent.ACTION_CALL,
                                        Uri.parse("tel:" + phone.replace("-", "")));
                                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    return;
                                }
                                startActivity(callIntent);
                            } else {
                                PermissionUtils.errorSinglePermission(granted);
                            }
                        }

                        @Override
                        public void onDenied(List<String> denied, boolean quick) {
                            PermissionUtils.errorPermission(getActivity(), denied, quick);
                        }
                    });
        } else {
            MyToast.show("电话号码为空");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();

    }

}
